package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.po.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

//通过@WebFilter（urlPattern = "/*")来拦截一切URL，然后在过滤器处理方法中选择
//放行不需要处理的URL，处理需要处理的url
@WebFilter(urlPatterns = "/*")
public class CheckLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
//request请求 response响应 chain调用链挨个处理请求，最后把请求到controller
//    CheckLoginFilter初始化的时候，把这个类的对象，放入到调用链表中

//    用于匹配uri路径的
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        强转servletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String uri = httpServletRequest.getRequestURI();
//        判断uri是否需要拦截
//        匹配原则 /backend/** /front/** /employee/login
//        如果不需要，直接放行
        List<String> urlIgnoreList = Arrays.asList("/backend/**",
                "/front/**", "/employee/login", "/employee/logout");
        boolean canIgnore = false;
        for (int i = 0; i < urlIgnoreList.size(); i++) {
             canIgnore = antPathMatcher.match(urlIgnoreList.get(i), uri);
             if(canIgnore){
                 filterChain.doFilter(servletRequest,servletResponse);
//                 加return,该方法直接结束，后续代码，不继续往下执行
                 return;
             }
        }
//        如果需要，通过session中的用户ID确定该用户是否登录过
        Long employeeId = (Long) httpServletRequest.getSession().getAttribute("employeeId");
        if(null == employeeId){
//            没登录，返回R类对象，msg为NOTLOGIN
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
//            加return，该方法直接结束，后续代码，不继续往下执行
            return;
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }



    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
